<template>

  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="30%"
    @close="handleClose"
  >
       <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" :disabled="form.id==-1?false:'disabled'"  />
        <el-alert
            v-if="form.id==-1"
            title="默认初始密码：123456"
            :closable="false"
            style="line-height: 10px;"
            type="success" >
        </el-alert>
      </el-form-item>

      <!-- 部门下拉选择 -->
      <el-form-item label="部门" prop="bumen">
        <el-select v-model="form.bumen" placeholder="请选择部门"
        @change="handleBumenChange" 
        clearable>
          <el-option
            v-for="item in bumenOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      
      <!-- 岗位下拉选择 -->
      <el-form-item label="岗位" prop="gangwei">
        <el-select v-model="form.gangwei" placeholder="请选择岗位" 
        :disabled="!form.bumen"
        clearable>
          <el-option
            v-for="item in gangweiOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="手机号" prop="phonenumber">
        <el-input v-model="form.phonenumber" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="'0'">正常</el-radio>
          <el-radio :label="'1'">禁用</el-radio>
        </el-radio-group>
      </el-form-item>


      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" :rows="4"/>
      </el-form-item>



    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose"
          >取消</el-button
        >
      </span>
    </template>
  </el-dialog>

</template>

<script setup>
import {defineEmits, defineProps,ref,watch } from "vue"
import requestUtil,{getServerUrl} from "@/util/request";
import { ElMessage } from 'element-plus'
import store from '@/store'
  
const props=defineProps(
    {
      id:{
        type:Number,
        default:-1,
        required:true
      },
      dialogTitle:{
        type:String,
        default:'',
        required:true
      },
      dialogVisible:{
        type:Boolean,
        default:false,
        required:true
      }
    }
)

const bumenOptions = ref([]) // 部门选项
const bumenOptions2 = ref([]) // 部门选项
const gangweiOptions = ref([]) // 岗位选项
const gangweiOptions2 = ref([]) // 岗位选项

// 在watch下方添加初始化方法
const initOptions = async () => {
  // 获取部门
  const bumenRes = await requestUtil.post("sys/bumen/all")
  if(bumenRes.data?.code === 200) {
    bumenOptions.value = bumenRes.data.list.map(item => item.bumen)
    bumenOptions2.value = bumenRes.data.list // 保留完整对象 [{id:1, bumen:"部门1"}]
  }
  //获取用户id
  const currentUser = ref(store.getters.GET_USERINFO);
  if (currentUser.value.bumenid) {
    const res = await requestUtil.post(`sys/gangwei/all?bumenId=`+currentUser.value.bumenid)
    if (res.data?.code === 200) {
      gangweiOptions.value = res.data.list.map(item => item.gangwei)
      gangweiOptions2.value = res.data.list // 保留完整对象 [{id:1, bumen:"部门1"}]
    }
  }
}

const form=ref({
  id:-1,
  username:"",
  password:"123456",
  status:"0",
  phonenumber:"",
  email:"",
  remark:"",
  bumen: "",    // 部门名称（用于显示）
  gangwei: "",   // 岗位名称（用于显示）
  bumenid: null, // 新增：部门ID（实际传值用）
  gangweiid: null // 新增：岗位ID（实际传值用）
})

const checkUsername = async (rule, value, callback) => {
  if(form.value.id==-1){
    const res=await requestUtil.post("sys/user/checkUserName",{username:form.value.username});
    if (res.data.code==500) {
      callback(new Error("用户名已存在！"));
    } else {
      callback();
    }
  }else{
    callback();
  }

}


const rules=ref({
  username:[
    { required: true, message: '请输入用户名'},
    { required: true, validator: checkUsername, trigger: "blur" }
  ],
  email: [{ required: true, message: "邮箱地址不能为空", trigger: "blur" }, { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
  phonenumber: [{ required: true, message: "手机号码不能为空", trigger: "blur" }, { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
  bumen: [{ required: true, message: '请选择部门', trigger: 'change' }],
  gangwei: [{ required: true, message: '请选择岗位', trigger: 'change' }]
})

const formRef=ref(null)

const initFormData=async(id)=>{
  const res=await requestUtil.get("sys/user/"+id);
  form.value = {
    ...res.data.sysUser,
    bumen: res.data.sysUser.bumen,    // 名称
    gangwei: res.data.sysUser.gangwei, // 名称
    bumenid: res.data.sysUser.bumenid, // ID
    gangweiid: res.data.sysUser.gangweiid // ID
  }
}

watch(
    ()=>props.dialogVisible,
    ()=>{
      initOptions() // 新增这行
      let id=props.id;
      console.log("id="+id)
      if(id!=-1){
        initFormData(id);
      }else{
        form.value={
          id:-1,
          username:"",
          password:"123456",
          status:"0",
          phonenumber:"",
          email:"",
          remark:""
        }
      }
    }
)

const emits=defineEmits(['update:modelValue','initUserList'])

const handleClose=()=>{
  emits('update:modelValue',false)
}

const handleConfirm=()=>{
  formRef.value.validate(async(valid)=>{
    if(valid){
      // 获取部门ID
      const selectedDept = bumenOptions2.value.find(item => item.bumen === form.value.bumen)
      // 获取岗位ID（需要确保gangweiOptions包含完整对象）
      const selectedPost = gangweiOptions2.value?.find(item => item.gangwei === form.value.gangwei)
      
      form.value.bumenid = selectedDept?.id;
      form.value.gangweiid =  selectedPost?.id;

      let result=await requestUtil.post("sys/user/save",form.value);
      let data=result.data;
      if(data.code==200){
        ElMessage.success("执行成功！")
        formRef.value.resetFields();
        emits("initUserList")
        handleClose();
      }else{
        ElMessage.error(data.msg);
      }
    }else{
      console.log("fail")
    }
  })
}


// 新增方法：部门变化时加载岗位
const handleBumenChange = async (bumen) => {  // 参数名改为bumen（与v-model一致）
  form.value.gangwei = "" // 清空已选岗位
  console.log("bumen",bumen);
  if (!bumen) return // 直接使用参数bumen
  
  // 获取部门ID（需要确保bumenOptions包含id）
  const bumenRes = await requestUtil.post("sys/bumen/all")
  const selectedDept = bumenRes.data.list.find(item => item.bumen === bumen)
  
  if (selectedDept?.id) {
    const res = await requestUtil.post(`sys/gangwei/all?bumenId=${selectedDept.id}`)
    if (res.data?.code === 200) {
      gangweiOptions.value = res.data.list.map(item => item.gangwei)
      gangweiOptions2.value = res.data.list // 保留完整对象 [{id:1, bumen:"部门1"}]
    }
  }
}

</script>

<style lang="scss" scoped>

</style>
